package models

import (
	"chongwu/utils/gorm_v2"
	"database/sql/driver"
	"fmt"
	"gorm.io/gorm"
	"strconv"
	"sync"
	"time"
)

type BaseModel struct {
	db       *gorm.DB
	DataBase string
}

type DBTime struct {
	time.Time
}

var (
	Instance map[string]*BaseModel
	once     sync.Once
)

func (b *BaseModel) setDataBase(database string) {
	b.DataBase = database
}

// 创建 userFactory
// 参数说明： 传递空值，默认使用 配置文件选项：UseDbType（mysql）
func (b *BaseModel) Model(isMaster bool) *gorm.DB {
	once.Do(func() {
		Instance = make(map[string]*BaseModel)
	})
	fmt.Println(b)

	if Instance[b.DataBase+strconv.FormatBool(isMaster)] == nil {
		Instance[b.DataBase+strconv.FormatBool(isMaster)] = &BaseModel{
			db: gorm_v2.UseDbConn(b.DataBase, isMaster),
		}
	}
	return Instance[b.DataBase+strconv.FormatBool(isMaster)].db
}

func (t DBTime) MarshalJSON() ([]byte, error) {
	output := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
	return []byte(output), nil
}

func (t DBTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *DBTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = DBTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
